/*
 * Copyright (c) 2023 by Kang Wang. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.egolessness.destino.client.scheduling.script;

import org.egolessness.destino.client.scheduling.support.ScheduledSupport;
import org.egolessness.destino.common.enumeration.ErrorCode;
import org.egolessness.destino.common.exception.DestinoException;

import javax.annotation.Nullable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Parameter;

public class AdapterScriptInstanceFactory implements ScriptInstanceFactory {

    @Override
    public Object createInstance(@Nullable Class<?> type) throws Exception {
        if (null == type) {
            return null;
        }
        for (Constructor<?> constructor : type.getConstructors()) {
            try {
                Parameter[] parameters = constructor.getParameters();
                Object[] paramValues = ScheduledSupport.paramInitValues(parameters);
                return constructor.newInstance(paramValues);
            } catch (Exception ignored) {
            }
        }

        throw new DestinoException(ErrorCode.UNEXPECTED_PARAM, "Failed to create instance for class " + type.getName());
    }
}
